package org.bopis.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.bopis.domain.UserContainer;
import org.bopis.form.LoginForm;
import org.bopis.service.ILoginService;
import org.bopis.service.impl.LoginService;

import com.boole.model.Usuario;

/**
 * Action que encargado de realizar la autenticacion de usuario en la aplicacion.
 * @author i-fernandezmolina
 **/
public class LoginAction extends CustomBaseAction {
  
  	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
  		//variables
  		Usuario usuario = null;
		String password = null;
		String email = null;
  		
		//obtenemos el email y password del usuario.
	    email = ((LoginForm)form).getEmail();
	    password = ((LoginForm)form).getPassword();	    
	    
	    //realizamos login
	    ILoginService loginservice = new LoginService();
	    usuario = loginservice.login(email, password);
	    
		if (usuario == null) {
			
			//el login ha sido fallido
			addActionError(request, "login.invalid", "login.invalid"); 
			return mapping.findForward("Failure");
			
		} else {
			
			// Metemos los datos del usuario en la sesion.
	    	UserContainer existingContainer = getUserContainer(request);
	    	existingContainer.setUsuario(usuario);
	    	return mapping.findForward("Success");
	    	
	    }
  	}
}